package com.niit.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.niit.pojo.CartItem;
import com.niit.pojo.Orders;
import com.niit.pojo.Product;
import com.niit.service.CartItemService;
import com.niit.service.OrdersService;
import com.niit.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.niit.utils.ByteArrayToBase64Adapter.GSON;

@RestController
@RequestMapping("/api/cartItem")
public class CartItemController {

    @Autowired
    private CartItemService cartItemService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ProductService productService;

    // 获取所有产品列表接口
    @RequestMapping("/list")
    public String getCartItemList(CartItem cartItem) {
        JsonObject jsonObject = new JsonObject();
        List<CartItem> cartItems = cartItemService.queryCartItem(cartItem);
        if(cartItems == null || cartItems.isEmpty()){
            jsonObject.addProperty("code", 0);
            jsonObject.addProperty("msg","购物车为空");
            return jsonObject.toString();
        }
        jsonObject.addProperty("code", 1);
        if(!cartItems.isEmpty()){
            jsonObject.addProperty("msg", "成功获取");
            jsonObject.add("success", GSON.toJsonTree(cartItems).getAsJsonArray());
        }
        return jsonObject.toString();
    }

    @RequestMapping("/add")
    public String addToCart(@RequestParam int uid, @RequestParam int pid, @RequestParam int quantity) {
        JsonObject jsonObject = new JsonObject();
        try {
            // 调用服务层方法，将商品加入购物车
            cartItemService.addToCart(uid, pid, quantity);
            jsonObject.addProperty("message", "加入购物车成功");
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            jsonObject.addProperty("message", "加入购物车失败：" + e.getMessage());
        }
        return jsonObject.toString();
    }

    @RequestMapping("/checkout")
    public String checkout(@RequestParam int uid, @RequestParam(required = false, defaultValue = "") String pid) {
        JsonObject json = new JsonObject();
        if(pid.equals("")) pid = null;

        //获取相应购物车列表并计算价格
        Map<String, Object> result = cartItemService.checkout(uid, pid == null?null:Integer.valueOf(pid));

        int code = (int) result.get("code");
        json.addProperty("code",  result.get("code").toString());
        if (code == 0) {
            json.addProperty("message", result.get("message").toString());
            return json.toString();
        }
        json.addProperty("totalPrice", result.get("totalPrice").toString());

        //将相应的购物车列表加入订单中
        List<CartItem> cartItems = (List<CartItem>) result.get("cartItems");
        if(cartItems == null || cartItems.isEmpty()){
            json.addProperty("code", 0);
            json.addProperty("message", "未获取到相应购物车列表");
            return json.toString();
        }

        cartItems.forEach(cartItem -> {
            Orders orders = new Orders(
                    cartItem.getProduct().getPid(),
                    cartItem.getUid(),
                    cartItem.getProduct().getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())),
                    cartItem.getQuantity());

            //先判断库存，库存足够才能被加到订单去
            Product product = productService.getProductById(cartItem.getProduct().getPid());
            product.setQuantity(product.getQuantity() - cartItem.getQuantity());
            if(product.getQuantity() >= 0){
                //加订单
                if(ordersService.addOrder(orders)) {
                    //加到订单后库存减少
                    productService.updateProduct(product);
                    //加到订单后删除购物车相应物品
                    cartItemService.deleteCartItem(cartItem.getUid(), cartItem.getProduct().getPid());
                }
            }
        });
        json.addProperty("message", "添加成功，请到订单列表查看您的订单");
        return json.toString();
    }

    @RequestMapping("/delete")
    public String deleteCartItem(@RequestParam int uid, @RequestParam int pid) {
        JsonObject jsonObject = new JsonObject();
        boolean isDeleted = cartItemService.deleteCartItem(uid, pid);
        if (isDeleted) {
            jsonObject.addProperty("code", 1);
            jsonObject.addProperty("message", "删除成功");
        } else {
            jsonObject.addProperty("code", 0);
            jsonObject.addProperty("message", "删除失败：未找到对应的购物车项");
        }
        return jsonObject.toString();
    }
}
